<template>
  <!-- 编码生成规则表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="50%"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="150"
      >
        <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
        <div class="search-container">
          <el-form-item label="规则编号" prop="ruleCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.ruleCode"
              placeholder="请输入规则编号"
              clearable
            />
            <span v-else>{{ formData.ruleCode }}</span>
          </el-form-item>
          <el-form-item label="规则名称" prop="ruleName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.ruleName"
              placeholder="请输入规则名称"
              clearable
            />
            <span v-else>{{ formData.ruleName }}</span>
          </el-form-item>
          <el-form-item label="编码长度" prop="codeLength">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.codeLength"
              placeholder="请输入编码长度"
              clearable
            />
            <span v-else>{{ formData.codeLength }}</span>
          </el-form-item>
          <el-form-item label="编码样例" prop="codeSample">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.codeSample"
              placeholder="请输入编码样例"
              clearable
            />
            <span v-else>{{ formData.codeSample }}</span>
          </el-form-item>
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.remarks"
              placeholder="请输入备注"
              clearable
            />
            <span v-else>{{ formData.remarks }}</span>
          </el-form-item>
        </div>
        <h4 class="mb-[20px] mt-[20px]">详细数据</h4>
        <el-card shadow="never" class="table-container">
          <template #header>
            <el-button
              type="success"
              plain
              @click="handleAdd"
              v-if="!props.isReadonly"
            >
              <i-ep-plus />
              新增</el-button
            >
          </template>
          <div class="formTable">
            <el-table
              :data="formData.details"
              style="width: 100%"
              :key="Math.random"
              border
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="60"
              />
              <el-table-column label="序号" props="seq" width="100">
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.seq'"
                    :rules="rules.sonseq"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.seq"
                      placeholder="请输入序号"
                      clearable
                    />
                    <span v-else>{{ row.seq }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="编码段类型"
                props="codeSectionType"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.codeSectionType'"
                    :rules="rules.soncodeSectionType"
                    label-width="0"
                  >
                    <el-select
                      v-if="!props.isReadonly"
                      v-model="row.codeSectionType"
                      clearable
                      placeholder="请选择编码段类型"
                    >
                      <el-option
                        v-for="item in dictionaryStore.filterDictList(
                          'CodeSectionType'
                        )"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                    <span v-else>{{
                      dictionaryStore.filterDictName(
                        "CodeSectionType",
                        row.codeSectionType
                      )
                    }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="编码长度"
                props="codeLength"
                min-width="100"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.codeLength'"
                    :rules="rules.soncodeLength"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.codeLength"
                      placeholder="请输入编码长度"
                      clearable
                    />
                    <span v-else>{{ row.codeLength }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="编码格式/固定值"
                props="codeFormat"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.codeFormat'"
                    :rules="rules.soncodeFormat"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.codeFormat"
                      placeholder="请输入编码格式"
                      clearable
                    />
                    <span v-else>{{ row.codeFormat }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="80"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.details.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                    ><i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "SYSTEMSYSCODERULEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  version: "",
  ruleCode: "",
  ruleName: "",
  codeLength: "",
  codeSample: "",
  lastBuildCode: "",
  remarks: "",
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  details: [
    {
      id: "",
      ruleId: "",
      seq: "",
      codeSectionType: "",
      codeLength: "",
      codeFormat: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  ruleCode: [{ required: true, message: "请输入规则编号", trigger: "blur" }],
  ruleName: [{ required: true, message: "请输入规则名称", trigger: "blur" }],
  codeLength: [{ required: true, message: "请输入编码长度", trigger: "blur" }],
  codeSample: [{ required: true, message: "请输入编码样例", trigger: "blur" }],
  sonruleId: [{ required: true, message: "请输入规则主键", trigger: "blur" }],
  sonseq: [{ required: true, message: "请输入序号", trigger: "blur" }],
  soncodeSectionType: [
    { required: true, message: "请输入编码段类型", trigger: "blur" },
  ],
  soncodeLength: [
    { required: true, message: "请输入编码长度", trigger: "blur" },
  ],
  soncodeFormat: [
    { required: true, message: "请输入编码格式", trigger: "blur" },
  ],
});

/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
};

const details = {
  id: "",
  ruleId: "",
  seq: "",
  codeSectionType: "",
  codeLength: "",
  codeFormat: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [details];
  formData.id = "";
  formData.version = "";
  formData.ruleCode = "";
  formData.ruleName = "";
  formData.codeLength = "";
  formData.codeSample = "";
  formData.lastBuildCode = "";
  formData.remarks = "";
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
}

const loading = ref(false);

/** 编码生成规则保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      // console.log("formData", toRaw(formData));
      await request({
        url: "/system/syscoderule/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/system/syscoderule/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}
:deep.el-input.el-input--default.el-input--suffix {
  // 固定宽度
  // width: 190px !important;
}
</style>
